﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace laohan.Common.Common
{
    public partial class API
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="lpszClass"></param>
        /// <param name="lpszWindow"></param>
        /// <returns></returns>
        [DllImport("user32.dll", EntryPoint = "FindWindow")]
        private static extern int FindWindow(string lpszClass, string lpszWindow);

        /// <summary>
        /// 
        /// </summary>
        /// <param name="hwndParent"></param>
        /// <param name="hwndChildAfter"></param>
        /// <param name="lpszClass"></param>
        /// <param name="lpszWindow"></param>
        /// <returns></returns>
        [DllImport("user32.dll", EntryPoint = "FindWindowEx")]
        private static extern int FindWindowEx(int hwndParent, int hwndChildAfter, string lpszClass, string lpszWindow);

        /// <summary>
        /// 
        /// </summary>
        /// <param name="hwnd"></param>
        /// <param name="lpRect"></param>
        /// <returns></returns>
        [DllImport("user32.dll", EntryPoint = "GetWindowRect")]
        private static extern int GetWindowRect(int hwnd, ref System.Drawing.Rectangle lpRect);

        /// <summary>
        /// 
        /// </summary>
        /// <param name="hwnd"></param>
        /// <param name="wMsg"></param>
        /// <param name="wParam"></param>
        /// <param name="lParam"></param>
        /// <returns></returns>
        [DllImport("user32.dll", EntryPoint = "SendMessage")]
        private static extern int SendMessage(int hwnd, int wMsg, int wParam, int lParam);

        /// <summary>
        /// 
        /// </summary>
        private static readonly int WM_MOUSEMOVE = 512;

        /// <summary>
        /// 刷新任务栏图标
        /// </summary>
        public static void RefreshTaskbarIcon()
        {

            int one = FindWindow("Shell_TrayWnd", null); //任务栏窗口

            int two = FindWindowEx(one, 0, "TrayNotifyWnd", null);//任务栏右边托盘图标+时间区

            int three = FindWindowEx(two, 0, "SysPager", null);//不同系统可能有可能没有这层

            int foor;//托盘图标窗口

            if (three > 0)
            {
                foor = FindWindowEx(three, 0, "ToolbarWindow32", null);
            }
            else
            {
                foor = FindWindowEx(two, 0, "ToolbarWindow32", null);
            }

            if (foor > 0)
            {
                System.Drawing.Rectangle r = new System.Drawing.Rectangle();

                GetWindowRect(foor, ref r);

                for (int x = 0; x < (r.Right - r.Left) - r.X; x++)//从任务栏左上角从左到右 MOUSEMOVE一遍，所有图标状态会被更新
                {
                    SendMessage(foor, WM_MOUSEMOVE, 0, (1 << 16) | x);
                }
            }
        }
    }
}